package com.soft.bams.server;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author yzh
 * @desc TODO
 * @date 2025/5/7
 */
public class ATMServer extends JFrame {

    private ServerPanel serverPanel;
    private RankPanel rankPanel;
    private ServerSocket serverSocket;
    private ExecutorService threadPool;
    private boolean isRunning = false;

    public ATMServer() {
        this.setTitle("ATM 服务器");
        this.setSize(800, 600);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setResizable(false);


        serverPanel = new ServerPanel(this);
        rankPanel = new RankPanel();

        threadPool = Executors.newCachedThreadPool();

        Container container = this.getContentPane();
        container.setLayout(new CardLayout());
        container.add(serverPanel, "server");
        container.add(rankPanel, "rank");

    }

    public void startServer(int port) {
        try {
            serverSocket = new ServerSocket(port);
            isRunning = true;
            JOptionPane.showMessageDialog(this, "服务已开启，端口: " + port);

            new Thread(() -> {
                while (isRunning) {
                    try {
                        Socket clientSocket = serverSocket.accept();
                        threadPool.execute(new ServerTask(clientSocket));
                    } catch (IOException e) {
                        if (isRunning) {
                            JOptionPane.showMessageDialog(this, "服务器异常: " + e.getMessage());
                        }
                    }
                }
            }).start();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "启动服务失败: " + e.getMessage());
        }
    }

    public void stopServer() {
        isRunning = false;
        try {
            if (serverSocket != null && !serverSocket.isClosed()) {
                serverSocket.close();
            }
            threadPool.shutdown();
            JOptionPane.showMessageDialog(this, "服务已关闭");
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "关闭服务异常: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        new ATMServer().setVisible(true);
    }
}
